// SF Interface
#function(sf_input /* 商飞输入文件 */, std_input /* 可选 */)
class SFInterface
{
    // 目标变量表
    self.target = table
    {
        info : table
        {
            folder : "";
            name   : ""
        };
        model    : [];
        material : [
            table
            {
                name : "pec";
                type : "pec"
            }
        ];

        cable    : [];
        probe    : [];
        surface  : [];

    };


    // 载入接口
    mfun.load = function(input_fn)
    {
        local data = io.handler.json.load(input_fn);

        local file_nfo = fs.filename(input_fn);
        logger.log_message("input file [%s]/[%s]", file_nfo.path, file_nfo.filename);
        if(file_nfo.path == '.')
        {
            println("bp1");
            this.target.info.folder = os.getcwd();
            logger.log_message("Using Current Working Dir: %s", os.getcwd());
        }else
        {
            println("bp2");
            this.target.info.folder = file_nfo.path;
        }
        this.target.info.name   = file_nfo.filename;

        for(k, v in data)
        {
            if(!is_nil(this[k]))
            {
                println("PROCESSING", k);
                this->(this[k])(v);
            }else
            {
                logger.log_warning("unsupported_feature: %s", k);
            }
        }
    };

    // 兼容处理单个属性是变量表的
    // 如果input是变量表，那么套一个数组的壳再返回
    local comp_table2vec = function(input, name)
    {
        if(is_table(input))
        {
            logger.log_message(_hT("compatible_mode in %s"), name);
            return [input];
        }else
        {
            return input;
        }
    };

    // 模型转换接口
    local translate_model = function(m)
    {
        local ret = table();
        local fn = fs.filename(m.FILE_NAME, m.FOLDER);
        ret.file = fn.fullpath; // 全路径直接设置到file属性
        ret.name = fn.name;     // 用文件名（去掉后缀）作为名称
        ret.material = m.MATERIAL;
        ret.format = m.FORMAT;
        return ret;
    };
    mfun.MODEL_INPUT = function(input)
    {
        for(i, v in input)
        {
            this.target.model[i] = translate_model(v);
        }
    };

    // 材料转换接口
    local translate_material = function(m)
    {
        local ret = table();
        ret.name = m.name;

        local in_type = string.lower(m.type);

        if(in_type == "simple")
        {
            // 简单材料
            ret.type = "simple";
            ret.epsilon = m.epsilon;
            ret.sigma_e = m.electric_conductivity;
            ret.mu = m.mu;
            ret.sigma_m = m.magnetic_conductivity;
        } else if(in_type == "lossy")
        {
            ret.type = "lossy";
            ret.epsilon = m.epsilon;
            ret.mu = m.mu;
            ret.tan_e = m.tangent_e;
            ret.tan_m = m.tangent_m;
        } else if(in_type == "dispersive")
        {
            // 色散材料
            // m.FILE_NAME
            // m.FILE_NAME_M
        } else
        {
            logger.log_warning(_hT("unsupported_material_type"));
        }
        return ret;
    };
    mfun.MATERIAL_PARAM = function(input)
    {
        input = comp_table2vec(input, "MATERIAL_PARAM");
        // 材料特殊处理：会预置部分默认材料（如PEC等）
        for(i, v in input)
        {
            this.target.material[end+1] = translate_material(v);
        }
    };

    // 输出设置
    local translate_output = function(m)
    {
        local ret = table();
        ret.file = fs.filename(m.FILE_NAME, m.FOLDER).fullpath;
        ret.fpath=m.FOLDER;
        return ret;
    };
    mfun.OUTPUT_SETTINGS = function(input)
    {
        // 这里直接设置即可
        this.target.output = translate_output(input);
    };

    // 激励设置
    local translate_signal = function(m)
    {
        local ret = table();

        if(m.TYPE == "HEMP")
        {
            // 标准HEMP：双指数信号
            ret.type = "doubleexp";
            ret.alpha = m.DECLINE_PARAM;
            ret.beta  = m.RISE_PARAM;
            ret.A     = m.TOP_ELECTRIC;
            ret.k     = m.CORRECTION_COEFFICIENT;
        }else if(m.TYPE == "IMPORT")
        {
            // 导入信号
            ret.type = "import";
            ret.filename = fs.filename(m.FILE, m.FOLDER).fullpath;
        }
        return ret;
    };

    local translate_source = function(m)
    {
        local ret = table();
        ret.theta = m.Dir_theta;
        ret.phi   = m.Dir_phi;
        ret.alpha = m.Dir_alpha;
        return ret;
    };
    local translate_unit = function(m)
    {
        local ret = table();
        ret.ul = m.UL;
        ret.uf = m.UF;
        ret.ut = m.UT;
        return ret;
    };
    local translate_freq = function(m)
    {
        local ret = table();
        ret.max = m.FREQ_MAX;
        ret.min = m.FREQ_MIN;
        ret.nsp = m.FREQ_FREQ_NUM;
        return ret;
    };
    local translate_time = function(m)
    {
        local ret = table();
        ret.max = m.TIME_MAX;
        return ret;
    };
    mfun.SIMULATION_PARAM = function(input)
    {
        
        this.target.unit = translate_unit(input);
        this.target.freq = translate_freq(input);
        this.target.time = translate_time(input);
        this.target.source = translate_source(input);

    };
    mfun.HEMP_WAVE = function(input)
    {
       
        this.target.signal = translate_signal(input);
    };


    // 场点监视器+ex区域场
    // 兼容文件模式和数组模式 数据检查
    local monitor_judge=function(data,m)
    {
       local arr_size = map(@(x){return length(x);},data);//判定定义的数据类型与长度是否一致
       local data_size=math.unique(arr_size);  //如果是[["1",1,2,3,4,5,6],["2",1,2,3,4,5,6]] 区域场
       if(length(data_size)>1)
       {           
           logger.log_error(format("ELECTRIC_FIELD_IN: %{1} define length is not consistent!",m.NAME));
           return 101;
       }
        else
       {
           local info=table()
           if(data_size[0]==1)
           {
               //math.mod(numel(data),3)
               info["mtype"]=1;   //[0无，1点 2面，3体，4远场/球]
               info["flag"]="point_array";
               return info;
           }
           else if(data_size[0]==4)
           {
               info["mtype"]=1;   // [0无，1点 2面，3体，4远场/球]
               info["flag"]="point_list";
               return info;
           }else if(data_size[0]==7)
           {
                local mytpe=[];
                local flag=[];
                for(local i=0;i<length(arr_size);i++)
                {   local xsize=data[i][4]-data[i][1];
                    local ysize=data[i][5]-data[i][2];
                    local zsize=data[i][6]-data[i][3];
                    if(all([xsize,ysize,zsize]>=0))
                    {
                        local index=math.find_index([xsize,ysize,zsize],0);
                        if (numel(index)==0)
                        {
                            mytpe[i]=3;
                            flag[i]="volume";
                            logger.log_message(format("Name %{1} is volume",data[i][0]));
                        }
                        else if(numel(index)==1)
                        {
                            mytpe[i]=2;
                            flag[i]=["yoz","zox","xoy"][index[0]];
                            logger.log_message(format("Name：%{1} is parallel %{2}",data[i][0],flag[i]));
                        }else
                        {
                            mytpe[i]=0;
                            flag[i]="none";
                            logger.log_message(format("Name %{1} setting errorm,exist %{2} dimsize is equal!",data[i][0],numel(index)));
                        }
                    }
                    else
                    {
                        mtype[i]=0;
                        flag[i]="none";
                        logger.log_warning(format("ELECTRIC_FIELD_IN: %{1}-%{2} define dimsize exist<0",m.NAME,data[i][0]));
                    }
                    
                }
                info["mtype"]=mytpe;
                info["flag"]=flag;
                return info;

           }else
           {
                logger.log_message(format("ELECTRIC_FIELD_IN:Data length of %{1} is %{2},unsupported_probe_type",m.Name,data_size[0]));
                return 101;
           }
       }

    };

    local translate_probe = function(m)
    {
        local ret = table();
        ret.name = m.NAME;
        ret.type = m.TYPE;    //时域或频域
        ret.fieldtype=m.FIELD_TYPE;  //记录场分量Ex、Ey、Ez、Evec、....
        ret.time = m.TIME;
        ret.freq = m.FREQ;
        ret.mtype= 1;      //[0->无，1->点，2->面，3->体，4远场/球]
        if(is_array(m.POSITION))
        {
            ret.inputtype = "data";
            ret.data = clone(m.POSITION);
            local info;
            info=monitor_judge(ret.data,m);
            if(is_table(info))
            {
                ret.mtype=info.mtype;
                ret.flag=info.flag;
            }
        }else
        {
            ret.inputtype = "file";
            ret.file = fs.filename(m.POSITION, m.FOLDER).fullpath; //不支持文件格式的体/区域场定义
        }
        return ret;
    };
    mfun.ELECTRIC_FIELD_IN = function(input)
    {
        // 单例属性兼容
        input = comp_table2vec(input, "ELECTRIC_FIELD_IN");
        for(i, v in input)
        {
            this.target.probe[i] = translate_probe(v);
        }
    };


    // 线缆设置
    local translate_cable = function(m)
    {
        local ret = table();
        ret.file = fs.filename(m.CABLE_PATH, m.FOLDER).fullpath;
        ret.core_radius=m.CABLE_DIAMETER_CORE;
        ret.core_mat = m.CABLE_MAT_CORE;
        ret.gnd_distance=m.CABLE_DISTANCE;
        ret.coat_thick=m.CABLE_THICKNESS_DIELEC;
        ret.coat_mat=m.CABLE_MAT_DIELEC;
		ret.name=m.NAME;
        return ret;
    };
    mfun.CABLE_PARAMETER = function(input)
    {
        // 单例属性兼容
        input = comp_table2vec(input, "CABLE_PARAMETER");
        for(i, v in input)
        {
            this.target.cable[i] = translate_cable(v);
        }
    };

    // 仿真检查
    local translate_check = function(m)
    {
        local ret = table();
        ret.file = fs.filename(m.FILE, m.FOLDER).fullpath;
        return ret;
    };

    mfun.SIMULATION_CHECK = function(input)
    {
        this.target.check = translate_check(input);
    };

};

local sfi = SFInterface();

sfi.load(sf_input);

return sfi.target;